<template>
  <div class="page-box" style="position: relative; flex-direction: row">
    <div class="field-config-page">
      <div class="page-header">
        <h2>{{ layerInfo.displayName || layerInfo.tableName }} 字段配置</h2>
      </div>

      <div class="field-config-content">
        <vxe-table
          class="row-height-mini"
          show-overflow
          border
          :data="tableFields"
          :row-config="rowConfig"
          :expand-config="expandConfig"
          :column-config="columnConfig"
          ref="fieldTable"
          @cell-click="handleFieldSelect"
        >
          <vxe-column type="expand" width="40">
            <template #content="{ row }">
              <div style="padding: 12px">
                <el-descriptions class="myel-description" :column="3" size="mini" border labelClassName="myel-label" content-class-name="myel-content">
                  <el-descriptions-item label="是否必填： ">
                    <el-switch
                      v-model="row.displayRule.isRequired"
                      active-text="是"
                      :active-value="1"
                      :inactive-value="0">
                    </el-switch>
                  </el-descriptions-item>

                  <!-- 当选择是编辑字段时显示的额外配置 -->
                  <el-descriptions-item label="控件类型： ">
                    <el-select
                      :size="defaultFormItemSize"
                      v-model="row.displayRule.inputType"
                      placeholder=""
                      :clearable="true"
                      :filterable="true"
                      @visible-change="controlTypeWidget.onVisibleChange"
                    >
                      <el-option
                        v-for="item in controlTypeWidget.dropdownList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item
                    label="数据字典： "
                    v-if="
                      row.displayRule.inputType === 'select_single' ||
                      row.displayRule.validateRule === 'select_multi' ||
                      row.displayRule.validateRule === 'cascader'
                    "
                  >
                    <el-select
                      :size="defaultFormItemSize"
                      v-model="row.displayRule.selectOptions"
                      placeholder=""
                      :clearable="true"
                      :filterable="true"
                      @visible-change="dictTypeWidget.onVisibleChange"
                    >
                      <el-option
                        v-for="item in dictTypeWidget.dropdownList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="校验规则： " :span="2">
                    <el-select
                      style="width: 100%; max-width: 100% !important"
                      :size="defaultFormItemSize"
                      multiple
                      width="100%"
                      v-model="row.displayRule.validateRule"
                      placeholder=""
                      :clearable="true"
                      :filterable="true"
                      @visible-change="validateRuleWidget.onVisibleChange"
                    >
                      <el-option
                        v-for="item in validateRuleWidget.dropdownList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item
                    label="最大值： "
                    v-if="
                      row.displayRule.validateRule.includes('maxValue') ||
                      row.displayRule.validateRule.includes('number') ||
                      row.displayRule.validateRule.includes('integer')
                    "
                  >
                    <el-input
                      v-model="row.displayRule.validateMaxValue"
                      type="number"
                      size="mini"
                    ></el-input>
                  </el-descriptions-item>

                  <el-descriptions-item
                    label="最小值： "
                    v-if="
                      row.displayRule.validateRule.includes('minValue') ||
                      row.displayRule.validateRule.includes('number') ||
                      row.displayRule.validateRule.includes('integer')
                    "
                  >
                    <el-input
                      v-model="row.displayRule.validateMinValue"
                      type="number"
                      size="mini"
                    ></el-input>
                  </el-descriptions-item>

                  <el-descriptions-item
                    label="最大长度： "
                    v-if="row.displayRule.validateRule.includes('maxLength')"
                  >
                    <el-input
                      v-model="row.displayRule.validateMaxLength"
                      type="integer"
                      size="mini"
                    ></el-input>
                  </el-descriptions-item>

                  <el-descriptions-item label="最小长度： " v-if="row.displayRule.validateRule.includes('minLength')">
                    <el-input v-model="row.displayRule.validateMinLength" type="integer" size="mini"></el-input>
                  </el-descriptions-item>

                  <el-descriptions-item
                    label="正则表达式： "
                    v-if="row.displayRule.validateRule.includes('regex')"
                  >
                    <el-input v-model="row.displayRule.validatePattern" size="mini"></el-input>
                  </el-descriptions-item>

<!--                  <el-descriptions-item label="是否依赖其他字段： >-->
<!--                    <el-switch-->
<!--                      v-model="row.displayRule.hasDependRelation"-->
<!--                      active-text="是"-->
<!--                      :active-value="1"-->
<!--                      :inactive-value="0">-->
<!--                    </el-switch>-->
<!--                  </el-descriptions-item>-->

<!--                  <el-descriptions-item-->
<!--                    label="依赖表达式： "-->
<!--                    v-if="row.displayRule.hasDependRelation === 1"-->
<!--                  >-->
<!--                    <el-input v-model="row.displayRule.dependRelation" size="mini"></el-input>-->
<!--                  </el-descriptions-item>-->
                </el-descriptions>
              </div>
            </template>
          </vxe-column>

          <vxe-column field="name" title="字段名" min-width="100" drag-sort></vxe-column>
          <vxe-column field="storageType" title="数据类型" min-width="100"></vxe-column>
          <vxe-column field="displayName" min-width="200" title="显示名">
            <template #default="{ row }">
              <el-input v-model="row.displayName" :size="defaultFormItemSize"></el-input>
            </template>
          </vxe-column>

          <vxe-column field="isLabelField" title="是否是注记" min-width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.isLabelField"
                active-text="是"
                :active-value="1"
                :inactive-value="0">
              </el-switch>
            </template>
          </vxe-column>
          <vxe-column field="isPopupDescField" title="是否弹窗显示" min-width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.isPopupDescField"
                active-text="是"

                :active-value="1"
                :inactive-value="0">
              </el-switch>
            </template>
          </vxe-column>
          <vxe-column field="isListDescField" title="是否列表显示" min-width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.isListDescField"
                active-text="是"
                :active-value="1"
                :inactive-value="0">
              </el-switch>
            </template>
          </vxe-column>
          <vxe-column field="isEditField" title="是否支持编辑" min-width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.isEditField"
                active-text="是"
                :active-value="1"
                :inactive-value="0">
              </el-switch>
            </template>
          </vxe-column>
          <vxe-column field="isSearchField" title="是否查询字段" min-width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.isSearchField"
                active-text="是"
                :active-value="1"
                :inactive-value="0">
              </el-switch>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="100" min-width="100">
            <template #default="{ row }">
              <el-button type="text" size="mini" @click="removeField(row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>

      <div class="page-footer">
        <el-button :size="defaultFormItemSize" @click="cancel" type="default">取消</el-button>
        <el-button :size="defaultFormItemSize" @click="saveConfig" type="primary">保存</el-button>
      </div>
    </div>
    <label class="page-close-box" @click="onCancel(true)">
      <img src="@/assets/img/back2.png" alt="" />
    </label>
  </div>
</template>

<script>
import { DictionaryController, LayerFieldController } from '@/api';
import { DropdownWidget } from '@/utils/widget';
import { LayerDefineController } from '@/api';

import {
  cachedPageChildMixin,
  cachePageMixin,
  statsDateRangeMixin,
  uploadMixin
} from '@/core/mixins';

export default {
  name: 'FieldConfigPage',
  props: {
    layerId: {
      type: [String, Number],
      required: true
    }
  },
  mixins: [
    cachePageMixin,
    cachedPageChildMixin,
    statsDateRangeMixin,
    uploadMixin
  ],
  data() {
    return {
      layerInfo: {},
      tableFields: [],
      selectedField: null,

      yesNoOptionsWidget: new DropdownWidget(this.loadYesNoDropdownList),
      controlTypeWidget: new DropdownWidget(this.loadControlTypeDropdownList),
      validateRuleWidget: new DropdownWidget(this.loadValidateRuleDropdownList),
      dictTypeWidget: new DropdownWidget(this.loadDictNameDropdownList),

      expandConfig: {
        showIcon: true,
        iconOpen: 'el-icon-arrow-down',
        iconClose: 'el-icon-arrow-right',
        visibleMethod({ row }) {
          return (row.isEditField === 1)
        }
      },
      columnConfig: {
        resizable: true
      },
      rowConfig: {
        drag: true
      }
    };
  },

  computed: {
    defaultFormItemSize() {
      return 'small';
    }
  },

  methods: {
    onCancel(isSuccess) {
      this.removeCachePage(this.$options.name);
      this.refreshParentCachedPage = isSuccess;
      this.$router.go(-1);
    },
    // 初始化数据
    async init() {
      try {
        // 加载字典数据
        await Promise.all([
          this.yesNoOptionsWidget.onVisibleChange(true),
          this.controlTypeWidget.onVisibleChange(true),
          this.validateRuleWidget.onVisibleChange(true),
          this.dictTypeWidget.onVisibleChange( true).catch(e => {})
        ]);

        // 获取图层信息和字段信息
        await this.loadLayerInfo();
      } catch (error) {
        this.$message.error('初始化数据失败: ' + error.message);
      }
    },

    // 获取图层信息
    async loadLayerInfo() {
      try {
        const res = await LayerDefineController.view(this, { id: this.layerId });
        this.layerInfo = res.data;
        console.log(this.layerInfo)
        // 获取字段信息
        await this.loadFieldList();
      } catch (error) {
        this.$message.error('获取图层信息失败: ' + error.message);
      }
    },

    // 获取字段列表
    async loadFieldList() {
      try {
        const res = await LayerFieldController.list(this, {
          layerFieldDtoFilter: {
            layerId: this.layerId
          },
          orderParam: [{
            fieldName: 'displaySort'
          }]
        });
        this.tableFields = res.data.dataList;
      } catch (error) {
        this.$message.error('获取字段列表失败: ' + error.message);
      }
    },

    // 选择字段显示编辑规则
    handleFieldSelect({ row }) {
      this.selectedField = row;
    },

    // 移除字段
    removeField(field) {
      this.$confirm('确定要删除该字段吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const index = this.tableFields.findIndex(f => f.id === field.id);
          if (index > -1) {
            this.tableFields.splice(index, 1);
            // 如果删除的是当前选中的字段，清空选中
            if (this.selectedField && this.selectedField.id === field.id) {
              this.selectedField = null;
            }
          }
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },

    // 保存配置
    saveConfig() {
      const saveData = {};
      const $table = this.$refs.fieldTable;
      if ($table) {
        const tableData = $table.getFullData();
        saveData[this.layerId] = tableData.map(((field, index) => ({
          ...field,
          displaySort: index
        })))
        LayerDefineController.batchUpdate(this, {layerFieldMap : saveData})
          .then(res => {
            this.$message.success('配置保存成功');
            this.onCancel(true)
          })
          .catch(e => {
            this.$message.error('配置保存失败: ' + e.message);
          });
      }
    },

    // 取消操作
    cancel() {
      this.onCancel(false)
    },

    /**
     * 字典数据加载方法
     */
    loadYesNoDropdownList() {
      return new Promise((resolve, reject) => {
        const params = {};
        DictionaryController.dictYesNoDict(this, params)
          .then(res => {
            resolve(res.getList());
          })
          .catch(e => {
            reject(e);
          });
      });
    },

    /**
     * 字典名称下拉数据获取函数
     */
    loadDictNameDropdownList() {
      return new Promise((resolve, reject) => {
        const params = {
        };
        DictionaryController.dictPmDict(this, params).then(res => {
          resolve(res.getList());
        }).catch(e => {
          reject(e);
        });
      });
    },

    loadValidateRuleDropdownList() {
      return new Promise((resolve, reject) => {
        const params = {};
        DictionaryController.dictCustomValidateRuleDict(this, params)
          .then(res => {
            resolve(res.getList());
          })
          .catch(e => {
            reject(e);
          });
      });
    },

    loadControlTypeDropdownList() {
      return new Promise((resolve, reject) => {
        const params = {};
        DictionaryController.dictCustomControlTypeDict(this, params)
          .then(res => {
            resolve(res.getList());
          })
          .catch(e => {
            reject(e);
          });
      });
    }
  },

  mounted() {
    this.init();
  }
};
</script>

<style scoped>
.field-config-page {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  width: 100%;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.field-config-content {
  margin-bottom: 20px;
}

.page-footer {
  text-align: center;
  padding: 10px 0;
  border-top: 1px solid #eee;
}

.row-height-mini ::v-deep .vxe-body--column {
  height: 35px !important;
}

::v-deep .myel-label {
  background: #E1F3D8 !important;
  width: 100px !important;
  text-align: right !important;
}
::v-deep .myel-content {
  width: 20% !important;
  max-width: 30% !important;
  text-align: left !important;
}
.myel-description {
  margin-right: 30px;
  margin-left: 30px;
}
</style>
